﻿using UnityEngine;
using System.Collections;

//------------------------------------------------------------
// shaco Framework
// Copyright © 2017-2021 chang.liu All rights reserved.
// Feedback: 449612236@qq.com
//------------------------------------------------------------

namespace shaco
{
    /// <summary>
    /// 游戏的启动组件，必须在整个游戏启动前运行，建议放到初始化场景中
    /// 如果是Unity5.3以上版本，则会自动执行，不需要手动放置
    /// </summary>
    [DisallowMultipleComponent]
    public class GameInitComponent : MonoBehaviour
    {
        static private bool _isInited = false;
        static GameInitComponent _instance;

        void Awake()
        {
            InitFrameworkEnvironment();
        }

        void Update()
        {
            MainUpdate(Time.deltaTime);
        }

        //为了防止游戏退出时候某些instance没有清理完毕报错
        //这里需要监听下OnApplicationQuit，这比在EditorMonoBehaviour.OnEnteredEditMode中处理更合适点
        void OnApplicationQuit()
        {
            ClearAllCacheInstance();
        }

        static public void ClearAllCacheInstance()
        {
            shaco.GameHelper.voice.StopAll();
            shaco.GameHelper.sound.StopAll();
            shaco.GameHelper.music.StopAll();
            shaco.GameHelper.res.UnloadUnusedAssetsAsync();
            shaco.GameHelper.action.StopAllAction();
            shaco.GameHelper.ui.ClearUI();
            shaco.GameHelper.objectpool.Clear();
            shaco.Base.WaitFor.StopAll();
            shaco.GameHelper.coroutine.StopAllWillStartCoroutine();
            shaco.GameHelper.observer.Clear();
            shaco.GameEntry.ClearIntances();
        }

        static public UnityEngine.Coroutine StartCoroutine2(IEnumerator coroutine)
        {
            if (null == _instance)
                InitFrameworkEnvironment();
            return _instance.StartCoroutine(coroutine);
        }

        static public void StopCoroutine2(IEnumerator coroutine)
        {
            if (null == _instance)
                InitFrameworkEnvironment();
            _instance.StopCoroutine(coroutine);
        }

        //初始化框架
        static public void InitFrameworkEnvironment()
        {
            if (_isInited)
                return;

            Debug.Log("<<<<<<<<<<GameInitComponent InitFrameworkEnvironment>>>>>>>>>>");
            _isInited = true;

            //这里需要临时获取一次来初始化框架组件配置读取
            var configTmp = shaco.GameHelper.gameConfig;

            //自动创建游戏初始化组件到场景中
            //已经场景中已经存在该组件，则将它属性修改为不销毁
            _instance = GameEntry.GetComponentInstance<GameInitComponent>();

            //初始化内存池回收对象
            shaco.GameEntry.GetComponentInstance<UnityObjectPoolCompnnet>();
        }

        /// <summary>
        /// 整个游戏计时器刷新方法
        /// </summary>
        static public void MainUpdate(float deltaTime)
        {
            shaco.Base.WaitFor.Update(deltaTime);
        }
    }
}
